package com.hao.controller;

import com.hao.dto.DailyStatisticsDTO;
import com.hao.service.StatisticsService;
import com.hao.task.DailyStatisticsTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 统计控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/statistics")
public class StatisticsController {
    
    @Autowired
    private StatisticsService statisticsService;
    
    @Autowired
    private DailyStatisticsTask dailyStatisticsTask;
    
    /**
     * 获取今日数据统计
     */
    @GetMapping("/today")
    public Map<String, Object> getTodayStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            DailyStatisticsDTO statistics = statisticsService.getTodayStatistics();
            
            result.put("code", 200);
            result.put("message", "获取统计数据成功");
            result.put("data", statistics);
            
        } catch (Exception e) {
            log.error("获取今日统计数据时发生异常：{}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "获取统计数据失败");
        }
        
        return result;
    }
    
    /**
     * 获取指定日期数据统计
     */
    @GetMapping("/{date}")
    public Map<String, Object> getDailyStatistics(@PathVariable String date) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            DailyStatisticsDTO statistics = statisticsService.getDailyStatistics(date);
            
            result.put("code", 200);
            result.put("message", "获取统计数据成功");
            result.put("data", statistics);
            
        } catch (Exception e) {
            log.error("获取{}统计数据时发生异常：{}", date, e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "获取统计数据失败");
        }
        
        return result;
    }
    
    /**
     * 手动触发统计任务（用于测试）
     */
    @PostMapping("/trigger")
    public Map<String, Object> triggerStatisticsTask() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("手动触发统计任务");
            dailyStatisticsTask.manualTrigger();
            
            result.put("code", 200);
            result.put("message", "统计任务触发成功");
            
        } catch (Exception e) {
            log.error("手动触发统计任务时发生异常：{}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "统计任务触发失败");
        }
        
        return result;
    }
} 